<script setup>
import { ref, reactive, toRaw } from "vue";
import SvgIcon from "@/components/svgIcon/index.vue";
import { useRouter, useRoute } from "vue-router";

import { login } from "@/api/login";
import { useI18n } from "vue-i18n";
const router = useRouter();
const route = useRoute();

const { t } = useI18n();

const formData = reactive({
  username: "",
  password: "",
});

const formRef = ref();

const rules = ref({
  username: [
    {
      required: true,
      message: t("login.username") + t("login.required"),
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: t("login.password") + t("login.required"),
      trigger: "blur",
    },
  ],
});

const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      // 模拟登录
      console.log("formData:", toRaw(formData));
      login(formData.username, formData.password).then(() => {
        const path = route.query.redirect || "/";
        router.push(path);
      });
    })
    .catch((error) => {
      console.log("error", error);
    });
};

const toRegister = () => {
  router.push({
    path: "/register",
    query: route.query,
  });
};
</script>

<template>
  <a-form :model="formData" ref="formRef" :rules="rules">
    <a-form-item name="username">
      <a-input
        v-model:value="formData.username"
        :placeholder="$t('login.username')"
      >
        <template #prefix>
          <SvgIcon name="UserOutlined" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item name="password">
      <a-input
        v-model:value="formData.password"
        type="password"
        :placeholder="$t('login.fillIn') + $t('login.password')"
      >
        <template #prefix>
          <SvgIcon name="LockOutlined" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-button
        type="primary"
        block
        @click="onSubmit"
        :disabled="formData.username === '' || formData.password === ''"
      >
        {{ $t("login.text") }}
      </a-button>
    </a-form-item>
    <a-form-item style="text-align: right; cursor: pointer" @click="toRegister">
      {{ $t("login.register") }}
    </a-form-item>
  </a-form>
</template>

<style lang='less' scoped>
.ant-form {
  margin-top: 46px !important;

  :deep(.ant-input-affix-wrapper) {
    line-height: 2.2;
  }

  .ant-btn {
    height: 42px;
  }
}
</style>